﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace CollabXT
{
    public partial class LinkerForm : Form
    {
        bool m_Connected;
        private WorkItemStore m_store;
        public LinkerForm()
        {
            m_Connected = false;
            InitializeComponent();
        }

        private void connectButton_Click(object sender, EventArgs e)
        {
            ICredentialsProvider provider = new UICredentialsProvider();
            TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(this.addressText.Text, provider);
            // Make sure you can continue.
            try
            {
                if (!m_Connected)
                {
                    // Try to authenticate. If unsuccessful, use tfsUICredProvider to
                    // request credentials.
                    tfs.Authenticate();
                    m_Connected = true;
                    this.buttonConnect.Text = "disconnect";
                    // Get the store
                    m_store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
                    // Populate the list of projects
                    this.comboBoxProject.Items.Clear();
                    foreach (Project proj in m_store.Projects)
                    {
                        this.comboBoxProject.Items.Add(proj.Name);
                    }
                    this.groupBoxProject.Show();
                }
                else
                {
                    m_Connected = false;
                    this.buttonConnect.Text = "connect";
                    this.groupBoxProject.Hide();
                }
            }
            catch (Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException)
            {
                // User cannot be authenticated. Shut down the application.
            }
            catch (System.Net.WebException)
            {
                // Problem connecting to the server
            }

        }

        private void LinkerForm_Load(object sender, EventArgs e)
        {

        }

        private void buttonLink_Click(object sender, EventArgs e)
        {
            this.toolStripStatusLabel.Text = "Linking";
            this.buttonLink.Enabled = false;
            
            Project currentProject = null;
            // there is definitely a better way to do this instead of reiterating the projects
            foreach (Project proj in m_store.Projects)
            {
                if (this.comboBoxProject.SelectedItem.ToString() == proj.Name.ToString())
                {
                    currentProject = proj;
                }
            }
            String qu_eps = "SELECT [System.Id], [VMXT.id] FROM WorkItems WHERE [System.TeamProject] = '" + currentProject.Name.ToString() + "' AND  [System.WorkItemType] = 'Entscheidungspunkt'";
            String qu_products = "SELECT [System.Id], [VMXT.id] FROM WorkItems WHERE [System.TeamProject] = '" + currentProject.Name.ToString() + "' AND  [System.WorkItemType] = 'Produkt'";
            String qu_activities = "SELECT [System.Id], [VMXT.id],[VMXT.EPRef],[VMXT.PRef] FROM WorkItems WHERE [System.TeamProject] = '" + currentProject.Name.ToString() + "' AND  [System.WorkItemType] = 'Aktivität'";
            // Execute the queries.
            WorkItemCollection epsCollection = m_store.Query(qu_eps);
            WorkItemCollection activitiesCollection = m_store.Query(qu_activities);
            WorkItemCollection productCollection = m_store.Query(qu_products);
            this.toolStripProgressBar.Maximum = activitiesCollection.Count;
            this.toolStripProgressBar.Value = 0;
            this.toolStripProgressBar.Visible = true;
            this.toolStripLinkNumber.Visible = true;
            int links=0;
            foreach (WorkItem wi in activitiesCollection)
            {
                //get the EP
                WorkItem ep = findWIByRef(wi.Fields["VMXT.EPRef"].Value.ToString(), epsCollection);
                //get the product
                WorkItem product = findWIByRef(wi.Fields["VMXT.PRef"].Value.ToString(), productCollection);
                //link them all together
                if (ep != null)
                {
                    wi.Links.Add(new RelatedLink(ep.Id));
                    links++;
                }
                if (product != null)
                {
                    wi.Links.Add(new RelatedLink(product.Id));
                    links++;
                }
                if (ep != null && product != null)
                {
                    product.Links.Add(new RelatedLink(ep.Id));
                    product.Save();
                    links++;
                }
                wi.Save();
                this.toolStripProgressBar.Value += 1;
                this.toolStripLinkNumber.Text = String.Format("Links {0}",links);
            }
            this.toolStripStatusLabel.Text = "Ready";
            this.toolStripProgressBar.Visible = false;
            this.toolStripLinkNumber.Visible = false;
            this.buttonLink.Enabled = true;
        }

        private WorkItem findWIByRef(string wiRef, WorkItemCollection wiCollection)
        {
            WorkItem ret = null;
            foreach (WorkItem it in wiCollection)
            {
                if (it.Fields["VMXT.id"].Value.ToString() == wiRef)
                {
                    ret = it;
                }
            }
            return ret;
        }
    }
}